package com.zhou.core.comm.weixin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.zhou.util.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zhouyongjun on 2020/7/15
 */
public class WeChatService {
        private static final Logger log = LoggerFactory.getLogger(WeChatService.class);
        private static WeChatService instance = new WeChatService();
        private  WeChatService(){}
        public static WeChatService getInstance()
        {
            return instance;
        }

    public String sendMessage(String corpid, String corpsecret,int agentid,JSONObject extraParams,String msgType,JSONObject contentJSON,String... users) throws IOException {
        String url = String.format(WeChatConst.SEND_MSG_URL, getAccessToken(corpid,corpsecret));
        JSONObject params = null;
        if (extraParams != null)
        {
            params = extraParams;
        }else
        {
            params  = new JSONObject();
        }
        if (users != null) {
            String touser = StringUtils.join(Arrays.asList(users), WeChatConst.SEPPARATOR);
            params.put(WeChatConst.touser,touser);
        }
        params.put(WeChatConst.agentid,agentid);
        params.put(WeChatConst.msgtype,msgType);
        params.put(msgType,contentJSON);
        return httpPost("UTF-8",url,params.toJSONString());
    }

    /**
     * 发送视频
     * @param corpid
     * @param corpsecret
     * @param agentid
     * @param media_id
     * @param extraParams
     * @param users
     * @return
     * @throws IOException
     */
    public String sendVideoMessage(String corpid, String corpsecret,int agentid,String media_id,String title,String description,JSONObject extraParams,String... users) throws IOException {
        JSONObject contentJSON = new JSONObject();
        contentJSON.put(WeChatConst.media_id,media_id);
        if(!StringUtils.isEmpty(title))
        {
            contentJSON.put(WeChatConst.title,title);
        }
        if(!StringUtils.isEmpty(description))
        {
            contentJSON.put(WeChatConst.description,description);
        }
        return sendMessage(corpid,corpsecret,agentid,extraParams,WeChatConst.MSGTYPE_VIDEO,contentJSON,users);
    }

    /**
     * 发送语言
     * @param corpid
     * @param corpsecret
     * @param agentid
     * @param media_id
     * @param extraParams
     * @param users
     * @return
     * @throws IOException
     */
    public String sendVoiceMessage(String corpid, String corpsecret,int agentid,String media_id,JSONObject extraParams,String... users) throws IOException {
        JSONObject contentJSON = new JSONObject();
        contentJSON.put(WeChatConst.media_id,media_id);
        return sendMessage(corpid,corpsecret,agentid,extraParams,WeChatConst.MSGTYPE_VOICE,contentJSON,users);
    }

    /**
     * 发送图片
     * @param corpid
     * @param corpsecret
     * @param agentid
     * @param media_id
     * @param extraParams
     * @param users
     * @return
     * @throws IOException
     */
    public String sendImageMessage(String corpid, String corpsecret,int agentid,String media_id,JSONObject extraParams,String... users) throws IOException {
        JSONObject contentJSON = new JSONObject();
        contentJSON.put(WeChatConst.media_id,media_id);
        return sendMessage(corpid,corpsecret,agentid,extraParams,WeChatConst.MSGTYPE_IMAGE,contentJSON,users);
    }

    /**
     * 发送文本内容
     * @param corpid
     * @param corpsecret
     * @param agentid
     * @param content
     * @param extraParams
     * @param users
     * @return
     * @throws IOException
     */
    public String sendTextMessage(String corpid, String corpsecret,int agentid,String content,JSONObject extraParams,String... users) throws IOException {
            JSONObject contentJSON = new JSONObject();
            contentJSON.put(WeChatConst.content,content);
           return sendMessage(corpid,corpsecret,agentid,extraParams,WeChatConst.MSGTYPE_TEXT,contentJSON,users);
        }



    /**
     * @Title  创建微信发送请求post实体，charset消息编码    ，contentType消息体内容类型，
     * url微信消息发送请求地址，data为post数据，token鉴权token
     * @param charset
     * @param url
     * @param data
     * @return
     * @throws IOException
     */
    public String httpPost(String charset,String url,String data) throws IOException {
        log.debug("httpPost url={},data={}",url,data);
        CloseableHttpClient httpclient = HttpClients.createDefault();
       HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new StringEntity(data, charset));
        CloseableHttpResponse response = httpclient.execute(httpPost);
        String resp;
        try {
            HttpEntity entity = response.getEntity();
            resp = EntityUtils.toString(entity, charset);
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
//        log.info("call [{}], param:{}, resp:{}", url, data, resp);
        return resp;
    }

    /**
     * corpid应用组织编号 corpsecret应用秘钥 获取toAuth(String
     * Get_Token_Url)返回结果中键值对中access_token键的值
     * @param
     */
    public String getAccessToken(String corpid, String corpsecret) throws IOException {
        try {
            String url = String.format(WeChatConst.GET_TOKEN_URL,corpid,corpsecret);
            String resp = httpGet(url);
//        System.out.println("resp=====:" + resp);
            Map<String, Object> map = JSON.parseObject(resp, new TypeReference<HashMap<String, Object>>(){});
            return map.get("access_token").toString();
        } catch (Exception e) {
            log.error("",e);
            return "";
        }
    }

    /**
     * 微信授权请求，GET类型，获取授权响应，用于其他方法截取token
     *
     * @param url
     * @return String 授权响应内容
     * @throws IOException
     */
    protected String httpGet(String url) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
       HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = httpClient.execute(httpGet);
        String resp = "";
        try {
            HttpEntity entity = response.getEntity();
            resp = EntityUtils.toString(entity, "utf-8");
            EntityUtils.consume(entity);
        } catch (Exception e) {
            log.error("",e);
        } finally {
            response.close();
        }
        LoggerFactory.getLogger(getClass()).info("httpGet url={} , resp:{}",url, resp);
        return resp;
    }
}
